﻿// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.Web.UI.WebControls;
using BlueOnionSoftware.Bloget.Properties;

namespace BlueOnionSoftware.Bloget
{
    internal class ContactView : View
    {
        private bool _disposed;
        private readonly TextBox _name = new TextBox();
        private readonly TextBox _email = new TextBox();
        private readonly TextBox _message = new TextBox();
        private readonly ConfirmedButton _submit = new ConfirmedButton();
        private readonly BlogetContactForm _contactForm;

        internal ContactView(BlogetContactForm blogetContactForm)
            : base(blogetContactForm)
        {
            _name.ID = "name";
            _email.ID = "email";
            _message.ID = "message";
            _submit.ID = "submit";
            _contactForm = blogetContactForm;
        }

        protected override void Dispose(bool managed)
        {
            try
            {
                if (_disposed == false)
                {
                    _disposed = true;

                    if (managed)
                    {
                        _name.Dispose();
                        _email.Dispose();
                        _message.Dispose();
                        _submit.Dispose();
                    }
                }
            }

            finally
            {
                base.Dispose(managed);
            }
        }

        protected override string RootClassId()
        {
            return "blog-contact";
        }

        protected override void ShowView()
        {
            Label(Resources.ContactFormNameLabel, _name.ID);
            RequiredTextBoxField(_name, string.Empty, string.Empty);
            Bloget.WriteLine("<br/>");

            Label(Resources.ContactFormEmailLabel, _email.ID);
            RequiredTextBoxField(_email, string.Empty, string.Empty);
            Bloget.WriteLine("<br/>");

            Label(Resources.ContactFormMessageLabel, _message.ID);
            _message.MaxLength = 2048;
            _message.TextMode = TextBoxMode.MultiLine;
            RequiredTextBoxField(_message, string.Empty, string.Empty);
            Bloget.WriteLine("<br/>");

            _submit.Command += SubmitCommand;
            SubmitButton(_submit, Resources.ContactFormSubmitLabel);
        }

        private void SubmitCommand(object sender, CommandEventArgs e)
        {
            if (Bloget.Page.IsValid)
            {
                var text = string.Format(Resources.ContactFormMessageFormat, _name.Text, _email.Text, _message.Text, Environment.NewLine);
                Bloget.SendEmail(Bloget.Blog.Webmaster, _contactForm.Subject ?? Resources.ContactFormMessageSubject, text);
                _contactForm.MessageSent();
            }
        }
    }
}